// 📦 S6 策略：S1 + S2 + S3 加权投票 + S4 连错淘汰
const select32NumbersByS1 = require("../v1/select32NumbersByS1.js");
const select32NumbersByS2 = require("../v2/select32NumbersByS2.js");
const select32NumbersByS3 = require("../v3/select32NumbersByS3.js");

const allNumbers = Array.from({ length: 49 }, (_, i) => (i + 1).toString().padStart(2, "0"));

const MAX_WRONG_STREAK = 5;
const S3_FREEZE_PERIOD = 100;

/**
 * 综合 S1+S2+S3 投票并应用 S4 淘汰规则
 * @param {Array} temp - 历史窗口数据
 * @param {Object} transitionMatrix - S3 用的转移矩阵
 * @param {Object} numberWrongMap - S4 连错记录
 * @param {number} currentIndex - 当前期索引
 * @returns {string[]} - 预测号码数组（32个）
 */
function select32NumbersByS6(temp, transitionMatrix, numberWrongMap, currentIndex) {
  const votes = {};
  allNumbers.forEach((num) => (votes[num] = 0));

  // ✅ 策略投票权重
  const weightS1 = 1.5;
  const weightS2 = 1.0;
  const weightS3 = 0.5;

  // ✅ 投票：S1
  const s1 = select32NumbersByS1(temp);
  s1.forEach((num) => (votes[num] += weightS1));

  // ✅ 投票：S2
  const s2 = select32NumbersByS2(temp);
  s2.forEach((num) => (votes[num] += weightS2));

  // ✅ 投票：S3（限制前100期冷启动）
  if (currentIndex > S3_FREEZE_PERIOD) {
    const s3 = select32NumbersByS3(temp, transitionMatrix);
    s3.forEach((num) => (votes[num] += weightS3));
  }

  // ✅ 根据票数排序
  const sorted = Object.entries(votes)
    .sort((a, b) => {
      if (b[1] !== a[1]) return b[1] - a[1];
      return a[0].localeCompare(b[0]);
    })
    .map(([num]) => num);

  // ✅ 应用 S4（剔除连续错太多的号码）
  const filtered = sorted.filter((num) => numberWrongMap[num] < MAX_WRONG_STREAK);

  // ✅ 补足至 32 个
  const excluded = new Set(filtered);
  const supplement = allNumbers.filter(
    (num) => !excluded.has(num) && numberWrongMap[num] < MAX_WRONG_STREAK
  );

  const finalSelected = [...filtered, ...supplement].slice(0, 32);
  return finalSelected;
}

module.exports = select32NumbersByS6;